﻿// Open Source: MIT License (http://www.opensource.org/licenses/mit-license.php)
// Project: YoProgramo.NET (http://code.google.com/p/yoprogramo/)
// Autor: Fabian Figueredo (info@fabianfigueredo.com.ar)
// Blog: blog.yoprogramo.net

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Practices.ServiceLocation;
using NHibernate.Validator.Engine;
using YoProgramo.Domain.BusinessLogic.Extensions;
using YoProgramo.Domain.Core.Entities;
using YoProgramo.Domain.Core.Exceptions;
using YoProgramo.Domain.Core.Interfaces;
using YoProgramo.Infrastructure.Tools.NHValidator;

namespace YoProgramo.Domain.BusinessLogic.Service
{
    public class CommentService : ICommentService {

        private ICommentRepository _CommentRepository;

        public CommentService(ICommentRepository commentrepository)
        {
            _CommentRepository = commentrepository;
        }

        #region ICommentService Members

        public NHibernate.Validator.Engine.InvalidValue[] Create(Comment comment) {
            try {
                InvalidValue[] validatorErrors = new NHValidatorWrapper<Comment>().Validate(comment);

                if (validatorErrors.Count() < 1)
                    _CommentRepository.SaveOrUpdate(comment);

                return validatorErrors;
            } catch (Exception ex) {
                throw new YPException("Error: Cannot create Comment", ex);
            }
        }

        public bool Update(Comment comment) {
            try {
                InvalidValue[] validatorErrors = new NHValidatorWrapper<Comment>().Validate(comment);

                if (validatorErrors.Count() < 1)
                    _CommentRepository.SaveOrUpdate(comment);

                return true;
            } catch {
                return false;
            }
        }

        public void Delete(Comment comment) {
            _CommentRepository.Delete(comment);
        }

        public IList<IComment> GetByStory(IStory story) {
            throw new NotImplementedException();
        }

        public IList<IComment> GetByUser(IUser user) {
            return (from s in _CommentRepository.GetAll()
                    where s.ByUser.Equals(user)
                    orderby s.CommentedAt descending
                    select s).ToList();
        }


        public IList<Comment> GetCleanComments(IList<Comment> comments) {
            return (from s in comments
                    where s.ByUser.IsActive && !s.ByUser.IsLockedOut && !s.IsSpam()
                    orderby s.CommentedAt ascending
                    select s).ToList();
        }

        #endregion
    }
}